package com.yitiao.simple.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取通道内的数据，接收客户端发来的消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("client [" + ctx.channel().remoteAddress() + "]:" + buf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 读操作完成后要做的事 —— 回复客户端
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 需要将 String 转成 Netty 的 ByteBuf
        ctx.writeAndFlush(Unpooled.copiedBuffer("收到...", CharsetUtil.UTF_8));
    }
}
